package com.iot.gateway.tsl.service.impl;

import com.iot.gateway.tsl.mapper.DeviceMapper;
import com.iot.gateway.tsl.model.DeviceEntity;
import com.iot.gateway.tsl.qo.DeviceQo;
import com.iot.gateway.tsl.service.TslDeviceService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TslDeviceServiceImpl implements TslDeviceService {

    private final DeviceMapper deviceMapper;

    public TslDeviceServiceImpl(DeviceMapper deviceMapper) {
        this.deviceMapper = deviceMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDevice(DeviceQo qo) {
        DeviceEntity e = new DeviceEntity();
        e.setId(Optional.ofNullable(qo.getId()).filter(id->!id.isEmpty())
                .orElse(UUID.randomUUID().toString()));
        e.setProductKey(qo.getProductKey());
        e.setName(qo.getName());
        deviceMapper.insert(e);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDevice(DeviceQo qo) {
        DeviceEntity e = new DeviceEntity();
        e.setId(qo.getId());
        e.setProductKey(qo.getProductKey());
        e.setName(qo.getName());
        deviceMapper.updateById(e);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDevice(String deviceId) {
        deviceMapper.deleteById(deviceId);
    }

    @Override
    public DeviceQo getDevice(String deviceId) {
        DeviceEntity e = deviceMapper.selectById(deviceId);
        if (e == null) return null;
        DeviceQo qo = new DeviceQo();
        qo.setId(e.getId());
        qo.setProductKey(e.getProductKey());
        qo.setName(e.getName());
        return qo;
    }

    @Override
    public List<DeviceQo> listDevices() {
        List<DeviceEntity> list = deviceMapper.selectList(null);
        return list.stream().map(e -> {
            DeviceQo qo = new DeviceQo();
            qo.setId(e.getId());
            qo.setProductKey(e.getProductKey());
            qo.setName(e.getName());
            return qo;
        }).collect(Collectors.toList());
    }
}
